/*
 *    Copyright 2022 The DSMS Authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.dsms.modules.filesystem.task;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.dsms.common.constant.RemoteResponseStatusEnum;
import com.dsms.common.constant.TaskStatusEnum;
import com.dsms.common.constant.TaskTypeEnum;
import com.dsms.common.remotecall.model.FailedDetail;
import com.dsms.common.remotecall.model.FinishedDetail;
import com.dsms.common.remotecall.model.RemoteResponse;
import com.dsms.common.taskmanager.TaskException;
import com.dsms.common.taskmanager.TaskStrategy;
import com.dsms.common.taskmanager.model.Task;
import com.dsms.common.taskmanager.service.ITaskService;
import com.dsms.dfsbroker.common.api.CommonApi;
import com.dsms.dfsbroker.filesystem.model.dto.FileSystemDTO;
import com.dsms.dfsbroker.filesystem.request.CreateFsRequest;
import com.dsms.modules.util.RemoteCallUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;


@Slf4j
@Service(TaskTypeEnum.TypeConstants.CREATE_FS)
public class CreateFsTask implements TaskStrategy {

    private static final int RETRY_TIME = 3;

    private final CommonApi commonApi;

    private final ITaskService taskService;

    @Autowired
    public CreateFsTask(CommonApi commonApi, ITaskService taskService) {
        this.commonApi = commonApi;
        this.taskService = taskService;
    }

    @Override
    public Task execute(Task task) {
        String taskParam = task.getTaskParam();
        if (ObjectUtils.isEmpty(taskParam)) {
            task.setTaskEndTime(LocalDateTime.now());
            task.setTaskErrorMessage("task parameter is null");
            task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
            return task;
        }
        FileSystemDTO fileSystemDTO = JSONUtil.toBean(taskParam, FileSystemDTO.class);
        try {
            RemoteResponse createFsResult = commonApi.getRequestResult(RemoteCallUtil.generateRemoteRequest(), RETRY_TIME, fileSystemDTO.getRequestId());
            if (Objects.equals(createFsResult.getState(), RemoteResponseStatusEnum.SUCCESS.getMessage())) {
                List<FinishedDetail> finished = createFsResult.getFinished();
                String resultMessage = StringUtils.hasText(finished.get(0).getOutb()) ? finished.get(0).getOutb() : finished.get(0).getOuts();
                if (resultMessage.startsWith(CreateFsRequest.CREATE_FS_SUCCESS)) {
                    task.setTaskEndTime(LocalDateTime.now());
                    task.setTaskStatus(TaskStatusEnum.FINISH.getStatus());
                    return task;
                } else {
                    task.setTaskEndTime(LocalDateTime.now());
                    task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
                    task.setTaskErrorMessage(resultMessage);
                    return task;
                }
            } else if (Objects.equals(createFsResult.getState(), RemoteResponseStatusEnum.FAILED.getMessage())) {
                List<FailedDetail> failed = createFsResult.getFailed();
                String failedMessage = StringUtils.hasText(failed.get(0).getOutb()) ? failed.get(0).getOutb() : failed.get(0).getOuts();
                task.setTaskErrorMessage(failedMessage);
                throw new TaskException("get create file system result fail,response:" + JSON.toJSONString(createFsResult));
            } else if (ObjectUtils.isEmpty(createFsResult.getState())) {
                task.setTaskErrorMessage(createFsResult.getMessage());
                throw new TaskException("unknown request state,response:" + JSON.toJSONString(createFsResult));
            }
        } catch (Throwable e) {
            log.error("create file system task failed, fail reason:{}", e.getMessage(), e);
            if (ObjectUtils.isEmpty(task.getTaskErrorMessage())) {
                task.setTaskErrorMessage(e.getMessage());
            }
            task.setTaskEndTime(LocalDateTime.now());
            task.setTaskStatus(TaskStatusEnum.FAIL.getStatus());
            return task;
        }
        task.setTaskStatus(TaskStatusEnum.QUEUE.getStatus());

        return task;
    }

    @Override
    public boolean validateTask(String[] validateParam) {
        return taskService.validateTaskMessageAndTaskType(validateParam[0]);
    }
}
